package com.sat.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rabbitmq.client.Channel;
import com.sat.goods.config.SkuFeign;
import com.sat.order.config.OrderRabbitMqConfig;
import com.sat.order.mapper.OrderItemMapper;
import com.sat.order.mapper.OrderMapper;
import com.sat.order.model.Order;
import com.sat.order.model.OrderItem;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
class OrderRabbimtMqListener {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private SkuFeign skuFeign;

    @RabbitListener(queues = OrderRabbitMqConfig.Dl_QUEUE)
    public void getMsg(Message message,Channel channel){
        byte[] body = message.getBody();
        //将字节转为字符串
        //拿到队列中的orderId
        String orderId = new String(body);
        System.out.println("我在这里"+orderId);

        //根据orderId查询订单状态
        Order order = orderMapper.selectById(orderId);
        String payStatus = order.getPayStatus();
       if ("0".equals(payStatus)){
           //说明没支付，那就回滚库存，设置订单状态为-1，表示订单已取消
           order.setOrderStatus("-1");
           orderMapper.updateById(order);

           //回滚库存
           //先根据orderId获取订单详情，在遍历所有订单，回滚库存
           QueryWrapper<OrderItem> queryWrapper=new QueryWrapper<>();
           queryWrapper.eq("order_id",orderId);
           List<OrderItem> orderItems = orderItemMapper.selectList(queryWrapper);
           for (OrderItem orderItem : orderItems) {
               //获取商品数量
               Integer num = orderItem.getNum();
               //调用skuFeign回滚库存
               skuFeign.updateInventory(orderItem.getSkuId().toString(),-num);
           }
       }


    }
}
